package com.adam.management.excel;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;


public class MutiThreadRead {

    private static Logger logger = LoggerFactory.getLogger(MutiThreadRead.class);
    /**
     * 多线程读取Excle 一个sheet一个线程
     * @param file
     */
    public void readExcel(MultipartFile file){

        try {
            //输入流
            InputStream inputStream = file.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            //sheet的总数量
            int sheetsSize = workbook.getNumberOfSheets();
            //创建线程池
            ExecutorService executorService = Executors.newFixedThreadPool(sheetsSize);
            //计数器
            CountDownLatch count = new CountDownLatch(sheetsSize);

            //创建多个有返回值的任务
            List<Future> futures = new ArrayList<>();

            for (int i=0; i<sheetsSize; i++){
                //这里需要重新赋值
                final int sheetIndex = i;
                MyCallable myCallable = new MyCallable(sheetIndex,file,count);
                //提交线程 获取返回值
                Future future = executorService.submit(myCallable);
                futures.add(future);
            }
            //阻塞主线程 除非CountDownLatch的计数器的值为0
            count.await();
            //关闭线程池
            executorService.shutdown();
            System.out.println("futures:"+futures.toString());

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
